package com.juyu.miliao.api.dao.redis;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Repository;

import com.juyu.miliao.api.domain.Visitor;
import com.juyu.miliao.api.util.RedisKeys;

@Repository
public class VisitorRedisDao {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
//	public List<Integer> getVisitors(int userId){
//		return stringRedisTemplate.boundZSetOps("user:" + userId + ":visitors").reverseRange(0, 50)
//		.stream()
//		.map(Integer::parseInt)
//		.collect(toList());
//	}
	
	public Boolean insertOrUpdateVisitor(Visitor entity){
		return stringRedisTemplate.opsForZSet().add(RedisKeys.ZSET_VISITORRECORD.getValue(entity.getIntervieweeUserId()), String.valueOf(entity.getVisitorUserId()),LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
	}
	
	public Optional<Long> findCountVisitor(long tokenUserId, long id){
		Long rank = stringRedisTemplate.opsForZSet().rank(RedisKeys.ZSET_VISITORRECORD.getValue(id), String.valueOf(tokenUserId));
		return Optional.ofNullable(rank);
	}

	public  List<Visitor> getVisitorIdsByUserId(long id, int startNum, int pageSize) {
		Set<TypedTuple<String>> visitors = stringRedisTemplate.opsForZSet().reverseRangeWithScores(RedisKeys.ZSET_VISITORRECORD.getValue(id), startNum, startNum + pageSize -1 );
		return	visitors.stream().map(v -> {
			return new Visitor(Integer.parseInt(v.getValue()),id,LocalDateTime.ofInstant(Instant.ofEpochMilli(v.getScore().longValue()), ZoneId.systemDefault()));
		}).collect(Collectors.toList());
	}
}
